<?php
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;

class NotificationController extends CloudControllerBase
{

    /******************************    质保邮件推送列表    ***********************************************************/

    //推送列表管理
    public function dispatchEmailAction()
    {

        if ($this->isMonitorAdminUser()) {
            $userList = $this->_getDispatchUsers();
            $this->view->setVars(array(
                "userList" => json_encode($userList)
            ));
        }

    }

    //更新推送列表
    public function updateDispatchEmailAction()
    {
        if ($this->isMonitorAdminUser()) {
            $targetAdd = $this->getPost("add");
            $targetRemove = $this->getPost("remove");
            $this->_doInsertOrDeleteDispatchEmail(true, $targetAdd);
            $this->_doInsertOrDeleteDispatchEmail(false, $targetRemove);
            $userList = $this->_getDispatchUsers();
            $this->returnJson($userList);
        } else {
            $this->returnAuthError();
        }
    }

    //获取当前邮件推送人列表
    private function _getDispatchUsers()
    {
        $sql = "select u.id,u.nickname,u.phone,u.email,u.icon_url,w.id as remind_id from (select * from bind_user_system where system_id=1) as b
left join user as u on  u.id=b.user_id 
left join warranty_mail as w on w.remindUser_id=b.user_id";
        $userList = $this->fetchAll($sql);
        return $userList;
    }

    //插入或者删除质保邮件人
    private function _doInsertOrDeleteDispatchEmail($isInsert, $data)
    {

        if (!empty($data)) {
            for ($i = 0; $i < count($data); $i++) {
                $userObj = $data[$i];
                $userId = intval($userObj['id']);
                $sql = "select * from warranty_mail where remindUser_id=$userId";
                $record = $this->fetchOne($sql);
                if ($isInsert) {
                    if (!empty($record)) {
                        $this->returnError("已添加用户:" . $userObj['uid'] . ",无法重复添加");
                    }
                } else {
                    if (empty($record)) {
                        $this->returnError("不存在该用户:" . $userObj['uid'] . ",无法删除");
                    }
                }
                $sql = "select * from user where id = $userId";
                $remindUser = $this->fetchOne($sql);
                if (empty($remindUser)) {
                    $this->returnError("没有该用户");
                } else {
                    if ($isInsert) {
                        $this->insert("warranty_mail", array(
                            "user_id" => $this->getMonitorLoginUser()->userId,
                            "remindUser_id" => $userId
                        ));
                    } else {

                        $deleteSql = "delete from warranty_mail where remindUser_id=$userId";
                        $this->execute($deleteSql);

                    }
                }
            }
        }
    }

    /******************************    自定义推送    ***********************************************************/

    public function ownPushNotiAction()
    {
        $user = $this->getMonitorLoginUser();

        if ($user->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $sql = "select id,nickname,phone from user";
            $userList = $this->fetchAll($sql);
        } elseif ($user->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN) {
            $sql = "select u.id,u.nickname,u.phone from bind_user_system as b,user as u where u.id=b.user_id and b.system_id={$user->subsystemId}";
            $userList = $this->fetchAll($sql);
        }
        $this->view->userList = json_encode($userList);
    }

    public function detailNotificationAction()
    {
        $user = $this->getMonitorLoginUser();
        $token = $this->getQuery("token");
        $tcpId = $this->getQuery("tcp_id");
        if (empty($token) && empty($tcpId)) {
            $this->transferErrorPage("未找到消息", "");
        } else {
            $where = "";
            if (!empty($token)) {
                $where = "token='$token'";
            }
            if (!empty($tcpId)) {
                $where = "id=$tcpId";
            }
            $data = $this->fetchOne("select p.id,p.data,p.created_at,t.read_state,user.nickname from
tcp_push_relation t left join tcp_push p on p.id=t.tcp_push_id left join user on user.id=t.from_id where t.$where");

            if (empty($data)) {
                $this->transferErrorPage("未找到消息", "");
            } else {
                //更新状态
                if ($data["read_state"] != 1) {
                    $this->update("tcp_push_relation", array(
                        "read_state" => 1
                    ), $where);
                }
                $msgData = json_decode($data['data']);
                $message = $msgData->message;
                $created_at = $data['created_at'];
                $nickName = $data['nickname'];
                $title = $message->title;
                $content = $message->content;

                $this->view->setVars(array(
                    "notification_title" => $title,
                    "notification_created_at" => $created_at,
                    "notification_user_name" => $nickName,
                    "notification_content" => $content
                ));
            }

        }

    }

    public function getMessageListAction()
    {

        $this->checkRequestParams(array(
            array(
                "key" => "start",
                "type" => "presence&number",
                "message" => "start为空"),
            array(
                "key" => "length",
                "type" => "presence&number",
                "message" => "length为空"),
        ));
        $start = $this->getPost("start");
        $length = $this->getPost("length");
        $user = $this->getMonitorLoginUser();
        $userId = $user->userId;
        $targetSql = " FROM tcp_push_relation t left join tcp_push p on t.tcp_push_id=p.id
where p.action='web_message' and t.to_id=$userId ";

        $countSql = "SELECT count(*) as total " . $targetSql;
        $total = $this->fetchColumn($countSql);

        $unReadCountSql = $countSql . " and read_state=0 ";
        $unReadTotal = $this->fetchColumn($unReadCountSql);

        $listSql = "SELECT t.id,p.data,p.created_at,t.read_state " . $targetSql . " order by p.created_at desc limit $start,$length";

        $data = $this->fetchAll($listSql);
        //总共
        $this->returnJson(array("total" => $total,
            "unread_total" => $unReadTotal,
            "data" => $data));
    }

    public function doNotiAllReadAction()
    {
        $user = $this->getMonitorLoginUser();
        $userId = $user->userId;
        $sql = "update tcp_push_relation set read_state=1 where to_id=$userId and read_state=0";
        $this->execute($sql);
        $this->returnSuccess();
    }

    public function doSendMessageAction()
    {

        $user = $this->getMonitorLoginUser();
        $this->checkRequestParams(array(
            array(
                "key" => "user",
                "type" => "presence",
                "message" => "请求用户参数错误"),
            array(
                "key" => "title",
                "type" => "presence",
                "message" => "标题不能为空"),
            array(
                "key" => "content",
                "type" => "presence",
                "message" => "内容不能为空"),
        ));

        // 获得数据
        $userIdArray = $this->getPost('user');
        $title = $this->getPost("title");
        $content = $this->getPost("content");
        $originContent = $this->getPost("originContent");
        $needSendEmail = $this->getPost("email");
        $needMonitor = $this->getPost("monitor");
        $needMsg = $this->getPost("msg");
        $needManager = $this->getPost("manager");
        $userArray = explode(",", $userIdArray);
        if (strlen($content) > 180) {
            $shortContent = substr($content, 0, 180);
        } else {
            $shortContent = $content;
        }
        for ($i = 0; $i < count($userArray); $i++) {
            $userId = $userArray[$i];
            if (empty($userId)) continue;
            $sql = "select id,email from user where id = $userId";
            $targetUser = $this->fetchOne($sql);
            if (empty($targetUser)) {
                $this->returnError("没有该用户");
            } else {

                if ($needMonitor) {
                    $token = $this->guid();
                    if (!$originContent) {
                        $originContent = $content;
                    }
                    $this->web_push(array(
                        'action' => 'web_message',
                        'status' => '2',
                        'data' => '',
                        'message' => array("title" => $title, "content" => $originContent, "shortContent" => $shortContent),
                        'token' => $token
                    ), $targetUser['id'], $user->userId);
                }
                if ($needSendEmail) {
                    if ($targetUser["email"]) {
                        $this->sendEmail($targetUser["email"], $title, $content);
                    }
                }
                if ($needManager) {
                    //管家推送
                }
                if ($needMsg) {
                    //短信推送
                }
            }
        }
        $this->returnSuccess("发送成功");
    }

    public function ownPushAction()
    {
        $user = $this->getMonitorLoginUser();

        if ($user->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $sql = "select id,nickname,phone from user";
            $userList = $this->fetchAll($sql);
        } elseif ($user->userRoleId == MonitorLoginUser::USER_ROLE_SUBSYSTEM_ADMIN) {
            $sql = "select u.id,u.nickname,u.phone from bind_user_system as b,user as u where u.id=b.user_id and b.system_id={$user->subsystemId}";
            $userList = $this->fetchAll($sql);
        }

        $this->view->userList = $userList;
    }

    public function addMailAction()
    {
        $user = $this->getMonitorLoginUser();

        if ($user->userRoleId == MonitorLoginUser::USER_ROLE_SYSTEM_ADMIN) {
            $sql = "select u.id,u.nickname,u.phone from bind_user_system as b,user as u where u.id=b.user_id and b.system_id=1";
            $userList = $this->fetchAll($sql);
        }

        $this->view->userList = $userList;
    }

    public function doAddMailAction()
    {
        $user = $this->getMonitorLoginUser();

        $validation = new Phalcon\Validation();
        $validation->add('user', new RegexValidator(array('pattern' => '/^[0-9]+$/', 'message' => '用户选择不正确')));
        $validation->add('user', new PresenceOf(array('message' => '没有选择用户')));
        $validation->add('mail', new RegexValidator(array('pattern' => '/^\w[-\w.+]*@feimarobotics.com$/', 'message' => '邮箱格式不正确')));
        $this->checkRequest($validation, $this->request->getPost());

        $userId = $this->getPost('user');
        $mail = $this->getPost('mail', '', 'email');
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "doAddMail userId:$userId, mail:$mail\r\n", FILE_APPEND);
        $expire = $this->redisExpire['user'];

        $sql = "select * from warranty_mail where mail = '$mail'";
        $record = $this->fetchOne($sql, $expire);
        if (!empty($record)) {
            $this->returnError("该邮箱已添加");
        }

        $sql = "select * from user where id = $userId";
        $remindUser = $this->fetchOne($sql, $expire);
        if (empty($remindUser)) {
            $this->returnError("没有该用户");
        } else {
            $sql = "select * from warranty_mail where remindUser_id = $userId";
            $warranty = $this->fetchOne($sql);

            if ($warranty) {
                $this->update("warranty_mail", array(
                    "user_id" => $user->userId,
                    "mail" => $mail,
                    "remindUser_id" => $userId),
                    'id=' . $warranty['id']);
            } else {
                $this->insert("warranty_mail", array(
                    "user_id" => $user->userId,
                    "mail" => $mail,
                    "remindUser_id" => $userId
                ));
            }
        }

        $this->returnSuccess('添加成功');
//         $this->returnJson(array('user'=>$userId,'mail'=>$mail));
//         $this->view->userList = $userList;
    }

    public function sendMessageAction()
    {

        $user = $this->getMonitorLoginUser();

        $validation = new Phalcon\Validation();
        $validation->add('user', new RegexValidator(array('pattern' => '/^[0-9]+$/', 'message' => '用户选择不正确')));
        $validation->add('user', new PresenceOf(array('message' => '没有选择用户')));
        $validation->add('message', new PresenceOf(array('message' => '消息不能为空')));
        $this->checkRequest($validation, $this->request->getPost());

        // 获得数据
        $userId = $this->getPost('user');
        $message = $this->getPost('message', '', 'striptags');
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "sendMessage userId:$userId, message:$message\r\n", FILE_APPEND);
        $expire = $this->redisExpire['user'];

        $sql = "select * from user where id = $userId";

        $toUser = $this->fetchOne($sql, $expire);
        if (empty($toUser)) {
            $this->returnError("没有该用户");
        } else {
            $this->web_push(array(
                'action' => 'web_message',
                'status' => '2',
                'data' => '',
                'message' => $message
            ), $toUser['id'], $user->userId);
        }

        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "sendMessage success", FILE_APPEND);
        $this->returnSuccess("发送成功。");
    }

    public function warrantyRecordAction()
    {
        $user = $this->getMonitorLoginUser();

        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {

                $this->postQueryByPage(array(
                    "id" => "ID",
                    "system_name" => "所属子系统",
                    "uas_serial_id" => "飞机编号",
                    "warranty_at" => "质保到期时间",
                    "warranty_kilometer" => "质保里程",
                    "insurance_at" => "第三方险到期时间",
                    "fuselage_at" => "机身险到期时间",
                    "maintain_kilometer" => "保养里程",
                    "created_at" => "发送时间"
                ), "(SELECT w.id,s.system_name,p.uas_serial_id,w.warranty_at,w.warranty_kilometer,w.insurance_at,w.fuselage_at,w.maintain_kilometer,w.created_at 
                        from warranty_to_user_record as w left JOIN subsystem_info as s on w.system_id=s.id, plane as p
                        where w.plane_id=p.id and w.toUser_id={$user->userId} order by w.created_at)", array(
                    ["system_name", "like", "%", "%"],
                    ["uas_serial_id", "like", "%", "%"]
                ), null, "id");
            };
                break;
        }
    }

    public function pushSettingAction()
    {

    }

    //推送日志列表
    public function listPushLogAction()
    {
        $user = $this->getMonitorLoginUser();

        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT r.*,p.action,p.data FROM tcp_push_relation r LEFT JOIN tcp_push p on p.id=r.tcp_push_id)";
                $this->postQueryByPage(array(
                    "tcp_push_id" => "推送ID",
                    "from_id" => "发送用户ID",
                    "to_id" => "推送用户ID",
                    "state" => "推送状态",
                    "created_at" => "发送时间",
                    "receive_at" => "接收时间",
                    "action" => "推送类型",
                    //"data" => "推送数据"
                ), $table, array(
                    ["from_id", "=", "", ""],
                    ["to_id", "=", "", ""],
                    ["state", "=", '', ''],
                    ["created_at_start", ">=", "", "", "created_at"],
                    ["created_at_end", "<=", "", "", "created_at"]
                ), "created_at desc", "id");
            };
                break;
        }
    }


    public function filedItemChanged($table, $name, $value)
    {
        $value = parent::filedItemChanged($table, $name, $value);

        switch ($name) {
            case "system_name": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "warranty_at": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "warranty_kilometer": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "insurance_at": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "fuselage_at": {
                if ($value == null) {
                    return "";
                }
            };
                break;
            case "maintain_kilometer": {
                if ($value == null) {
                    return "";
                }
            };
                break;
        }
        return $value;
    }

    private function sendMailtoUser($userid)
    {
        $warranty_at = date('Y-m-d', strtotime('30 day'));

        $sql = "SELECT p.id,p.uas_serial_id,a.name as area_name,s.system_name,b.system_id,p.name,p.company,p.phone,p.buy_at,p.warranty_at,p.warranty_kilometer,p.contacts,
                 p.address,u.mil,p.insurance_end_at,p.fuselage_end_at FROM plane as p left join plane_area as a on p.plane_area_id=a.id left join (select max(uas_odometer_value) as 
                mil,uas_serial_id FROM uas_status GROUP BY uas_serial_id) as u on p.uas_serial_id=u.uas_serial_id left join bind_plane_system as b on p.id=b.plane_id 
                left JOIN subsystem_info as s on b.system_id=s.id 
                where (p.uas_serial_id like '%FF%' or p.uas_serial_id like '07JD%' or p.uas_serial_id like '11VK%') and p.warranty_at<='$warranty_at' or mil>=3000 or insurance_end_at<='$warranty_at' or fuselage_end_at<='$warranty_at'";
        $planes = $this->fetchAll($sql);

        $sql = "SELECT * FROM warranty_to_user_record where toUser_id in ( $userid )";
        $allRecords = $this->fetchAll($sql);
        $planeRecords = array();
        $records = array();
        $result = 0;
        foreach ($allRecords as $allRecord) {
            $planeRecords[$allRecord['toUser_id']][$allRecord['plane_id']][] = $allRecord;
        }

        require_once dirname(__FILE__) . './../plugins/phpmailer/class.phpmailer.php';
        require_once dirname(__FILE__) . './../plugins/phpmailer/class.smtp.php';

        $sql = "select id, email from user where id in ( $userid )";
        $mails = $this->fetchAll($sql);
        foreach ($mails as $mail) {
            $userRecords = $planeRecords[$mail['id']];
            $userRecord = array();
            foreach ($userRecords as $planeRecord) {

                $dateAry = array();
                foreach ($planeRecord as $val) {
                    $dateAry [] = $val ['created_at'];
                }
                array_multisort($dateAry, SORT_DESC, $planeRecord);
                $userRecord [$planeRecord [0]['plane_id']] = $planeRecord [0];
                unset ($dateAry);

            }
            $warrantyPlanes = array();
            $content = '';
            foreach ($planes as $plane) {
                if ($userRecord[$plane['id']]) {
                    if (strtotime($userRecord[$plane['id']]['created_at']) < strtotime($plane['warranty_at'])) {
                        if (strtotime($userRecord[$plane['id']]['created_at']) < (strtotime($plane['warranty_at']) - 86400 * 30) && time() >= (strtotime($plane['warranty_at']) - 86400 * 30) && time() < strtotime($plane['warranty_at'])) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        } elseif (strtotime($userRecord[$plane['id']]['created_at']) >= (strtotime($plane['warranty_at']) - 86400 * 30) && strtotime($userRecord[$plane['id']]['created_at']) < strtotime($plane['warranty_at']) && strtotime($plane['warranty_at']) <= time()) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        }
                    }
                    if (strtotime($userRecord[$plane['id']]['created_at']) < strtotime($plane['insurance_end_at'])) {
                        if (strtotime($userRecord[$plane['id']]['created_at']) < (strtotime($plane['insurance_end_at']) - 86400 * 30) && time() >= (strtotime($plane['insurance_end_at']) - 86400 * 30) && time() < strtotime($plane['insurance_end_at'])) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        } elseif (strtotime($userRecord[$plane['id']]['created_at']) >= (strtotime($plane['insurance_end_at']) - 86400 * 30) && strtotime($userRecord[$plane['id']]['created_at']) < strtotime($plane['insurance_end_at']) && strtotime($plane['insurance_end_at']) <= time()) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        }
                    }
                    if (strtotime($userRecord[$plane['id']]['created_at']) < strtotime($plane['fuselage_end_at'])) {
                        if (strtotime($userRecord[$plane['id']]['created_at']) < (strtotime($plane['fuselage_end_at']) - 86400 * 30) && time() >= (strtotime($plane['fuselage_end_at']) - 86400 * 30) && time() < strtotime($plane['fuselage_end_at'])) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        } elseif (strtotime($userRecord[$plane['id']]['created_at']) >= (strtotime($plane['fuselage_end_at']) - 86400 * 30) && strtotime($userRecord[$plane['id']]['created_at']) < strtotime($plane['fuselage_end_at']) && strtotime($plane['fuselage_end_at']) <= time()) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        }
                    }
                    if ($plane['mil'] > 4500) {
                        if (empty($userRecord[$plane['id']]['warranty_kilometer'])) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        } elseif ($userRecord[$plane['id']]['warranty_kilometer'] < 5000 && $plane['mil'] >= 5000) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        }
                    }
                    if ($plane['mil'] > 3000) {
                        if (empty($userRecord[$plane['id']]['maintain_kilometer'])) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        } elseif (floor(($userRecord[$plane['id']]['maintain_kilometer'] - 3000) / 2000) < floor(($plane['mil'] - 3000) / 2000)) {
                            $warrantyPlanes[] = $plane;
                            continue;
                        }
                    }
                } else {
                    $warrantyPlanes[] = $plane;
                }

                $warrantyAlls[$plane['id']] = $plane;
            }

            if (count($warrantyPlanes) > 0) {
                //                 $t_contents = $t_contents."<br>".project_get_field( $p_project_id , 'name' ).":<br>";
                $content = $content . '<BODY"><h2 style="text-align: center; font-size: 24px; font-family: PingFangSC-Regular, Microsoft YaHei, sans-serif;">质保信息提醒</h2>
                        <table cellpadding="12" cellspacing="0" border="1" bordercolor="#979797" style="font-family: PingFangSC-Regular, Microsoft YaHei, sans-serif; margin: 0 auto; border-collapse: collapse;">
                        <tr style="color: #8C8C8C; font-size: 13px;">
                            <th style="white-space: nowrap;">飞机编号</th>
                            <th style="white-space: nowrap;">大区</th>
                            <th style="white-space: nowrap;">持有单位</th>
                            <th style="white-space: nowrap;">联系电话</th>
                            <th style="white-space: nowrap;">所属子系统</th>
                            <th style="white-space: nowrap;">当前飞行里程</th>
                            <th style="white-space: nowrap;">质保里程</th>
                            <th style="white-space: nowrap;">保养里程</th>
                            <th style="white-space: nowrap;">质保到期时间</th>
                            <th style="white-space: nowrap;">第三方险到期时间</th>
                            <th style="white-space: nowrap;">机身险到期时间程</th>
                        </tr>';
                foreach ($warrantyPlanes as $warrantyPlane) {
                    $warranty_kilometer = null;
                    $maintain_kilometer = null;

                    $content = $content . '<TR style="TEXT-ALIGN: center">
<TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['uas_serial_id'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['area_name'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['name'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['phone'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['system_name'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['mil'] . '</TD>';

                    if (empty($warrantyPlane['mil'])) {
                        $content = $content . '<TD></TD>';
                    } else {
                        if (4500 <= $warrantyPlane['mil'] && $warrantyPlane['mil'] < 5000) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">剩余' . (5000 - $warrantyPlane['mil']) . '公里</LABEL></TD>';
                        } elseif ($warrantyPlane['mil'] >= 5000) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">超出' . ($warrantyPlane['mil'] - 5000) . '公里</LABEL></TD>';
                        } else {
                            $content = $content . '<TD></TD>';
                        }
                    }

                    if (empty($warrantyPlane['mil'])) {
                        $content = $content . '<TD></TD>';
                    } else {
                        if (3000 <= $warrantyPlane['mil'] && $warrantyPlane['mil'] < 5000) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">超出' . ($warrantyPlane['mil'] - 3000) . '公里</LABEL></TD>';
                        } elseif ($warrantyPlane['mil'] >= 5000) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">超出' . (($warrantyPlane['mil'] - 3000) % 2000) . '公里</LABEL></TD>';
                        } else {
                            $content = $content . '<TD></TD>';
                        }
                    }

                    if (empty($warrantyPlane['warranty_at'])) {
                        $content = $content . '<TD></TD>';
                    } else {
                        $now_str = time();
                        $warr_begin = strtotime($warrantyPlane['warranty_at']) - 86400 * 30;
                        $warr_end = strtotime($warrantyPlane['warranty_at']);

                        if (time() >= (strtotime($warrantyPlane['warranty_at']) - 86400 * 30) && time() < strtotime($warrantyPlane['warranty_at'])) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">' . $warrantyPlane['warranty_at'] . '(剩余' . ceil((strtotime($warrantyPlane['warranty_at']) - time()) / 86400) . '天)</LABEL></TD>';
                        } elseif (time() >= strtotime($warrantyPlane['warranty_at'])) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">' . $warrantyPlane['warranty_at'] . '(超出' . ceil((time() - strtotime($warrantyPlane['warranty_at'])) / 86400) . '天)</LABEL></TD>';
                        } else {
                            $content = $content . '<TD></TD>';
                        }
                    }

                    if (empty($warrantyPlane['insurance_end_at'])) {
                        $content = $content . '<TD></TD>';
                    } else {
                        if (time() >= (strtotime($warrantyPlane['insurance_end_at']) - 86400 * 30) && time() < strtotime($warrantyPlane['insurance_end_at'])) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">' . $warrantyPlane['insurance_end_at'] . '(剩余' . ceil((strtotime($warrantyPlane['insurance_end_at']) - time()) / 86400) . '天)</LABEL></TD>';
                        } elseif (time() >= strtotime($warrantyPlane['insurance_end_at'])) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">' . $warrantyPlane['insurance_end_at'] . '(超出' . ceil((time() - strtotime($warrantyPlane['insurance_end_at'])) / 86400) . '天)</LABEL></TD>';
                        } else {
                            $content = $content . '<TD></TD>';
                        }
                    }

                    if (empty($warrantyPlane['fuselage_end_at'])) {
                        $content = $content . '<TD></TD>';
                    } else {
                        if (time() >= (strtotime($warrantyPlane['fuselage_end_at']) - 86400 * 30) && time() < strtotime($warrantyPlane['fuselage_end_at'])) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">' . $warrantyPlane['fuselage_end_at'] . '(剩余' . ceil((strtotime($warrantyPlane['fuselage_end_at']) - time()) / 86400) . '天)</LABEL></TD>';
                        } elseif (time() >= strtotime($warrantyPlane['fuselage_end_at'])) {
                            $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">' . $warrantyPlane['fuselage_end_at'] . '(超出' . ceil((time() - strtotime($warrantyPlane['fuselage_end_at'])) / 86400) . '天)</LABEL></TD>';
                        } else {
                            $content = $content . '<TD></TD>';
                        }
                    }

                    if ($warrantyPlane['mil'] >= 4500) {
                        $warranty_kilometer = $warrantyPlane['mil'];
                    }
                    if ($warrantyPlane['mil'] >= 3000) {
                        $maintain_kilometer = $warrantyPlane['mil'];
                    }

                    $this->insert('warranty_to_user_record', array(
                        "system_id" => $warrantyPlane['system_id'],
                        "plane_id" => $warrantyPlane['id'],
                        "from_user_id" => 0,
                        "insurance_at" => $warrantyPlane['insurance_end_at'],
                        "fuselage_at" => $warrantyPlane['fuselage_end_at'],
                        "warranty_at" => $warrantyPlane['warranty_at'],
                        "warranty_kilometer" => $warranty_kilometer,
                        "maintain_kilometer" => $maintain_kilometer,
                        "toUser_id" => $mail['id']
                    ));
                }

                $content = $content . '</TR></TBODY></TABLE>
                                    <HR style="HEIGHT: 1px; WIDTH: 210px" align=left color=#b5c4df SIZE=1>
                        
                                    <DIV><SPAN id=_FoxFROMNAME>cloud_service</SPAN></DIV></BODY>';
                if (!empty($mail['email'])) {
                    if ($this->sendEmail($mail['email'], $content, '质保信息提醒') == 'success') {
                        $result++;
                    }
                }

                $this->web_push(array(
                    'action' => 'web_warranty',
                    'status' => '2',
                    'data' => '',
                    'message' => '您有新的质保信息',
                    'token' => $this->guid()
                ), $mail['id'], 0);
                $this->tcp_push(array(
                    'action' => 'tcp_warranty',
                    'status' => '2',
                    'data' => '',
                    'message' => '您有新的质保信息'
                ), $mail['id'], 0);
            }
        }

        if (count($warrantyAlls) > 0) {
            //                 $t_contents = $t_contents."<br>".project_get_field( $p_project_id , 'name' ).":<br>";
            $content = '<h2 style="text-align: center; font-size: 24px; font-family: PingFangSC-Regular, Microsoft YaHei, sans-serif;">质保信息提醒</h2>
                        <table cellpadding="12" cellspacing="0" border="1" bordercolor="#979797" style="font-family: PingFangSC-Regular, Microsoft YaHei, sans-serif; margin: 0 auto; border-collapse: collapse;">
                        <tr style="color: #8C8C8C; font-size: 13px;">
                            <th style="white-space: nowrap;">飞机编号</th>
                            <th style="white-space: nowrap;">大区</th>
                            <th style="white-space: nowrap;">持有单位</th>
                            <th style="white-space: nowrap;">联系电话</th>
                            <th style="white-space: nowrap;">所属子系统</th>
                            <th style="white-space: nowrap;">当前飞行里程</th>
                            <th style="white-space: nowrap;">质保里程</th>
                            <th style="white-space: nowrap;">保养里程</th>
                            <th style="white-space: nowrap;">质保到期时间</th>
                            <th style="white-space: nowrap;">第三方险到期时间</th>
                            <th style="white-space: nowrap;">机身险到期时间程</th>
                        </tr>';
            foreach ($warrantyAlls as $warrantyPlane) {
                $warranty_kilometer = null;
                $maintain_kilometer = null;

                $content = $content . '<TR style="TEXT-ALIGN: center">
<TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['uas_serial_id'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['area_name'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['name'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['phone'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['system_name'] . '</TD>
                        <TD style="font-weight: bold; font-size: 16px; white-space: nowrap;">' . $warrantyPlane['mil'] . '</TD>';

                if (empty($warrantyPlane['mil'])) {
                    $content = $content . '<TD></TD>';
                } else {
                    if (4500 <= $warrantyPlane['mil'] && $warrantyPlane['mil'] < 5000) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">剩余' . (5000 - $warrantyPlane['mil']) . '公里</LABEL></TD>';
                    } elseif ($warrantyPlane['mil'] >= 5000) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">超出' . ($warrantyPlane['mil'] - 5000) . '公里</LABEL></TD>';
                    } else {
                        $content = $content . '<TD></TD>';
                    }
                }

                if (empty($warrantyPlane['mil'])) {
                    $content = $content . '<TD></TD>';
                } else {
                    if (3000 <= $warrantyPlane['mil'] && $warrantyPlane['mil'] < 5000) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">超出' . ($warrantyPlane['mil'] - 3000) . '公里</LABEL></TD>';
                    } elseif ($warrantyPlane['mil'] >= 5000) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">超出' . (($warrantyPlane['mil'] - 3000) % 2000) . '公里</LABEL></TD>';
                    } else {
                        $content = $content . '<TD></TD>';
                    }
                }

                if (empty($warrantyPlane['warranty_at'])) {
                    $content = $content . '<TD></TD>';
                } else {
                    $now_str = time();
                    $warr_begin = strtotime($warrantyPlane['warranty_at']) - 86400 * 30;
                    $warr_end = strtotime($warrantyPlane['warranty_at']);

                    if (time() >= (strtotime($warrantyPlane['warranty_at']) - 86400 * 30) && time() < strtotime($warrantyPlane['warranty_at'])) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">' . $warrantyPlane['warranty_at'] . '(剩余' . ceil((strtotime($warrantyPlane['warranty_at']) - time()) / 86400) . '天)</LABEL></TD>';
                    } elseif (time() >= strtotime($warrantyPlane['warranty_at'])) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">' . $warrantyPlane['warranty_at'] . '(超出' . ceil((time() - strtotime($warrantyPlane['warranty_at'])) / 86400) . '天)</LABEL></TD>';
                    } else {
                        $content = $content . '<TD></TD>';
                    }
                }

                if (empty($warrantyPlane['insurance_end_at'])) {
                    $content = $content . '<TD></TD>';
                } else {
                    if (time() >= (strtotime($warrantyPlane['insurance_end_at']) - 86400 * 30) && time() < strtotime($warrantyPlane['insurance_end_at'])) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">' . $warrantyPlane['insurance_end_at'] . '(剩余' . ceil((strtotime($warrantyPlane['insurance_end_at']) - time()) / 86400) . '天)</LABEL></TD>';
                    } elseif (time() >= strtotime($warrantyPlane['insurance_end_at'])) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">' . $warrantyPlane['insurance_end_at'] . '(超出' . ceil((time() - strtotime($warrantyPlane['insurance_end_at'])) / 86400) . '天)</LABEL></TD>';
                    } else {
                        $content = $content . '<TD></TD>';
                    }
                }

                if (empty($warrantyPlane['fuselage_end_at'])) {
                    $content = $content . '<TD></TD>';
                } else {
                    if (time() >= (strtotime($warrantyPlane['fuselage_end_at']) - 86400 * 30) && time() < strtotime($warrantyPlane['fuselage_end_at'])) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D59E1F;">' . $warrantyPlane['fuselage_end_at'] . '(剩余' . ceil((strtotime($warrantyPlane['fuselage_end_at']) - time()) / 86400) . '天)</LABEL></TD>';
                    } elseif (time() >= strtotime($warrantyPlane['fuselage_end_at'])) {
                        $content = $content . '<TD><LABEL style="margin: 0; padding: 1px 30px; border-radius: 20px; color: white; font-size: 15px; white-space: nowrap; background-color: #D51F1F;">' . $warrantyPlane['fuselage_end_at'] . '(超出' . ceil((time() - strtotime($warrantyPlane['fuselage_end_at'])) / 86400) . '天)</LABEL></TD>';
                    } else {
                        $content = $content . '<TD></TD>';
                    }
                }

                if ($warrantyPlane['mil'] >= 4500) {
                    $warranty_kilometer = $warrantyPlane['mil'];
                }
                if ($warrantyPlane['mil'] >= 3000) {
                    $maintain_kilometer = $warrantyPlane['mil'];
                }
            }

            $content = $content . '</TR></TBODY></TABLE>
                                    <HR style="HEIGHT: 1px; WIDTH: 210px" align=left color=#b5c4df SIZE=1>
                    
                                    <DIV><SPAN id=_FoxFROMNAME>cloud_service</SPAN></DIV>';
        }

        return $content;
    }
}